package com.zhijian.medical.service.impl;

import com.zhijian.medical.config.Constants;
import com.zhijian.medical.entity.dto.PersonDto;
import com.zhijian.medical.service.CacheService;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.redis.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.function.Function;

/**
 * @author HCG
 * @version 1.0
 * @date 2021/7/6
 */
@Service
@Slf4j
public class CacheServiceImpl implements CacheService {

    @Autowired
    private RedisConfig redisConfig;

    /**
     * {@inheritDoc}
     */
    @Override
    public Jedis support() {
        Jedis jedis = redisConfig.getResourceJedis();
        jedis.select(0);
        return jedis;
    }

    private <T> T execute(Function<Jedis, T> fuc) {
        Jedis jedis = null;
        try {
            jedis = support();
            return fuc.apply(jedis);
        } finally {
            if (null != jedis) {
                try {
                    jedis.close();
                } finally {

                }
            }
        }
    }

    @Override
    public String get(String key) {
        return execute(jedis -> jedis.get(key));
    }

    @Override
    public Long incr(String key) {
        return execute(jedis -> jedis.incr(key));
    }


    @Override
    public Long ttl(String key) {
        return execute(jedis -> jedis.ttl(key));
    }

    @Override
    public String set(String key, String value) {
        return execute(jedis -> jedis.set(key, value));
    }

    @Override
    public String setex(String key, int seconds, String value) {
        return execute(jedis -> jedis.setex(key, seconds, value));
    }

    @Override
    public Long del(String key) {
        return execute(jedis -> jedis.del(key));
    }

    @Override
    public PersonDto getPersonDtoByToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String userJson = get(String.format(Constants.Redis.TOKEN_LOGIN_USER, token));
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
        return JsonUtil.toBean(userJson, PersonDto.class);
    }
}
